package mspbots.data.tl.prod.jira.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultMessageModel;
import mspbots.data.tl.prod.jira.mapper.JiraWorklogMapper;
import mspbots.data.tl.prod.jira.model.JiraWorklog;
import mspbots.data.tl.prod.jira.service.JiraWorklogService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Jay.Yang
 */

@Service
@Log4j2
@DS("master")
public class JiraWorklogServiceImpl extends AbstractBaseServiceImpl<JiraWorklogMapper, JiraWorklog>
        implements JiraWorklogService {

    @Override
    public void sync(ResultMessageModel model) {
        if (ObjectUtils.isEmpty(model.getEntity()) || !ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            log.error("jira.worklog.tl entry is null,or Action No Add");
            return;
        }
        JsonNode node = model.getEntity();
        JiraWorklog data = JiraWorklog.builder()
                .worklogId(node.get("id").asLong())
                .issueId(node.get("issueId").asLong())
                .comment(node.get("comment").asText())
                .authorDisplayName(node.get("author").get("displayName").asText())
                .timeSpent(node.get("timeSpent").asText())
                .timeSpentSeconds(node.get("timeSpentSeconds").asLong())
                .createTime(!ObjectUtils.isEmpty(node.get("created"))
                        ? LocalDateTime.parse(node.get("created").asText().substring(0,19), DateTimeFormatter.ISO_DATE_TIME) : null)
                .updateTime(!ObjectUtils.isEmpty(node.get("updated"))
                        ? LocalDateTime.parse(node.get("updated").asText().substring(0,19), DateTimeFormatter.ISO_DATE_TIME) : null)
                .starteTime(!ObjectUtils.isEmpty(node.get("started"))
                        ? LocalDateTime.parse(node.get("started").asText().substring(0,19), DateTimeFormatter.ISO_DATE_TIME) : null)
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(model.getTenantId());
        JiraWorklog dbData = super.baseMapper.selectOne(Wrappers.<JiraWorklog>lambdaQuery()
                .eq(JiraWorklog::getTenantCode, data.getTenantCode())
                .eq(JiraWorklog::getWorklogId, data.getWorklogId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);
        }
    }
}
